package com.ljx.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Company: 上海数惠系统技术有限公司
 * Department: 数据中心：研发二部
 * Date: 2021/04/11 11:24
 *
 * @Author: Ljxpa
 * Email: lujx@dist.com.cn
 * Desc:
 */
@Component(value = "routingDataSource")
public class DetermineDatasourceImpl extends AbstractRoutingDataSource {

	@Autowired
	@Qualifier("readDataSource")
	private DataSource readDataSource;

	@Autowired
	@Qualifier("writeDataSource")
	private DataSource writeDataSource;

	@Override
	protected Object determineCurrentLookupKey() {
		DatasourceTypeEnum typeKey = DatasourceContextHolder.getReadOrWrite();
		Assert.notNull(typeKey, "数据库路由发现typeKey is null，无法抉择使用哪个库");
		System.out.println("使用：" + typeKey);
		return typeKey;
	}

	@Override
	public void afterPropertiesSet() {
		Map<Object,Object> targetDataSources=new HashMap<>();
		targetDataSources.put(DatasourceTypeEnum.READ, readDataSource);
		targetDataSources.put(DatasourceTypeEnum.WRITE, writeDataSource);
		//设置目标数据源
		this.setTargetDataSources(targetDataSources);
		//设置默认数据源
		this.setDefaultTargetDataSource(writeDataSource);
		//执行原有afterPropertiesSet逻辑，
		//即将targetDataSources中的DataSource加载到resolvedDataSources
		super.afterPropertiesSet();
	}
}
